"use client";

import React, { useState, useEffect, useCallback } from "react";
import {
  Button,
  message,
  Spin,
  Empty,
  Pagination,
  Modal,
  Breadcrumb,
} from "antd";
import { authFetch } from "@/utils/auth";
import { HeartOutlined } from "@ant-design/icons";
import { UserFavoriteModel } from "@/apis";
import { useRouter } from "next/navigation";
import Image from "next/image";
import type { BreadcrumbProps } from "antd";

// 工具函数：处理图片URL
const getFullImageUrl = (relativePath?: string) => {
  if (!relativePath) return "/images/default-product.png";
  if (relativePath.startsWith("http")) return relativePath;
  const ossBaseUrl = "https://oss.tz-group.com/";
  const cleanPath = relativePath.startsWith("/")
    ? relativePath.slice(1)
    : relativePath;
  return `${ossBaseUrl}${cleanPath}`;
};

const FavoritesPage: React.FC = () => {
  const [favorites, setFavorites] = useState<UserFavoriteModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [pageSize] = useState(12);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const router = useRouter();

  // 面包屑配置
  const getBreadcrumbItems = (): BreadcrumbProps["items"] => {
    return [
      {
        title: (
          <span onClick={() => router.push("/")} className="cursor-pointer">
            首页
          </span>
        ),
        key: "home",
      },
      {
        title: "我的收藏",
        key: "favorites",
      },
    ];
  };

  // 检查登录状态
  useEffect(() => {
    const checkLoginStatus = () => {
      const userInfo = localStorage.getItem("userInfo");
      const token = localStorage.getItem("token");

      if (userInfo && token) {
        setIsLoggedIn(true);
      } else {
        setIsLoggedIn(false);
        setShowLoginModal(true);
      }
    };

    checkLoginStatus();

    // 监听登录状态变化
    const handleUserInfoChange = () => {
      checkLoginStatus();
    };

    window.addEventListener("userInfoChanged", handleUserInfoChange);
    window.addEventListener("storage", handleUserInfoChange);

    return () => {
      window.removeEventListener("userInfoChanged", handleUserInfoChange);
      window.removeEventListener("storage", handleUserInfoChange);
    };
  }, [router]);

  // 获取收藏列表
  const fetchFavorites = useCallback(
    async (page: number = 1) => {
      if (!isLoggedIn) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);

        // 获取用户信息中的token
        const userInfo = localStorage.getItem("userInfo");
        if (!userInfo) {
          message.error("请先登录");
          return;
        }

        const userInfoObj = JSON.parse(userInfo);
        const jwtToken = userInfoObj.token;

        if (!jwtToken) {
          message.error("登录信息无效，请重新登录");
          return;
        }

        // 直接调用我们的API
        const response = await authFetch(
          `/api/favorite?condition.page=${page}&condition.size=${pageSize}`,
          {
            method: "GET",
          }
        );

        const data = await response.json();

        if (response.ok && data.success) {
          setFavorites(data.data?.data || []);
          setTotalItems(data.data?.total || 0);
        } else {
          message.error(data.message || "获取收藏列表失败");
        }
      } catch (error) {
        console.error("获取收藏列表失败:", error);
        message.error("获取收藏列表失败，请稍后重试");
      } finally {
        setLoading(false);
      }
    },
    [pageSize, isLoggedIn]
  );

  useEffect(() => {
    fetchFavorites(currentPage);
  }, [currentPage, fetchFavorites]);

  // 处理分页变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 处理产品点击
  const handleProductClick = (productId: number | undefined) => {
    if (!productId) return;
    router.push(`/products/${productId}`);
  };

  // 处理收藏/取消收藏
  const handleFavoriteToggle = async (
    productId: number | undefined,
    isFavorited: boolean
  ) => {
    if (!productId) return;

    try {
      // 获取用户信息中的token
      const userInfo = localStorage.getItem("userInfo");
      if (!userInfo) {
        message.error("请先登录");
        return;
      }

      const userInfoObj = JSON.parse(userInfo);
      const jwtToken = userInfoObj.token;

      if (!jwtToken) {
        message.error("登录信息无效，请重新登录");
        return;
      }

      if (isFavorited) {
        // 取消收藏
        const response = await authFetch(
          `/api/favorite/remove?productId=${productId}`,
          {
            method: "POST",
          }
        );

        const data = await response.json();

        if (response.ok && data.success) {
          setFavorites((prev) =>
            prev.filter((item) => item.productId !== productId)
          );
          message.success("已取消收藏");
        } else {
          message.error(data.message || "取消收藏失败");
        }
      } else {
        // 添加收藏
        const response = await authFetch(
          `/api/favorite?productId=${productId}`,
          {
            method: "POST",
          }
        );

        const data = await response.json();

        if (response.ok && data.success) {
          message.success("已添加到收藏");
          // 刷新收藏列表
          fetchFavorites(currentPage);
        } else {
          message.error(data.message || "添加收藏失败");
        }
      }
    } catch (error) {
      console.error("操作失败:", error);
      message.error("操作失败，请稍后重试");
    }
  };

  // 处理登录弹窗
  const handleLoginModalOk = () => {
    setShowLoginModal(false);
    router.push("/login");
  };

  const handleLoginModalCancel = () => {
    setShowLoginModal(false);
    router.push("/");
  };

  // 如果未登录，显示空白页面（等待弹窗）
  if (!isLoggedIn) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Modal
          title="提示"
          open={showLoginModal}
          onOk={handleLoginModalOk}
          onCancel={handleLoginModalCancel}
          okText="去登录"
          cancelText="返回首页"
          centered
        >
          <p>登录后才能执行此操作</p>
        </Modal>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        {/* 面包屑导航 */}
        <div className="mb-6">
          <Breadcrumb items={getBreadcrumbItems()} separator=">" />
        </div>

        {/* 收藏列表 */}
        {loading ? (
          <div className="flex justify-center items-center py-20">
            <Spin size="large" />
          </div>
        ) : favorites.length === 0 ? (
          <div className="flex justify-center items-center py-20">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="暂无收藏产品"
            />
          </div>
        ) : (
          <>
            <div className="w-full grid gap-4 md:grid-cols-2 xl:grid-cols-3">
              {favorites.map((item) => {
                const productImg = item.mainPhotoes?.[0]?.attachmentAddress;
                const fullImageUrl = getFullImageUrl(productImg || "");
                const currentGrade = item.grade || "A";
                const allGrades = [
                  { grade: "A", label: "A", color: "#027F3F" },
                  { grade: "B", label: "B", color: "#68D300" },
                  { grade: "C", label: "C", color: "#FFB422" },
                  { grade: "D", label: "D", color: "#FF8738" },
                ];

                return (
                  <div
                    key={item.id}
                    className="bg-white shadow-md p-4 flex cursor-pointer hover:shadow-lg transition-shadow duration-300 border-[#E0E0E0]"
                    onClick={() => handleProductClick(item.productId)}
                  >
                    <div className="relative w-[180px] h-[180px] flex-shrink-0">
                      <Image
                        src={fullImageUrl}
                        alt={item.productName || "产品图片"}
                        width={180}
                        height={180}
                        className="object-cover"
                      />
                      <div className="absolute top-2 left-2">
                        <Button
                          type="primary"
                          danger
                          size="small"
                          icon={<HeartOutlined />}
                          className="shadow-lg hover:shadow-xl"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleFavoriteToggle(item.productId, true);
                          }}
                          title="取消收藏"
                        >
                          取消收藏
                        </Button>
                      </div>
                    </div>
                    <div className="text-sm flex-1 ml-4">
                      <h2 className="flex justify-between">
                        <div className="text-sm font-bold text-[#2F2F2F] line-clamp-2">
                          {item.productName || "未命名产品"}
                        </div>
                        <div className="text-[#2CD39C] px-2 border border-[#33D598] bg-[#F2FFF4]">
                          {item.coreTarget || "无目标"}
                        </div>
                      </h2>
                      <p className="text-[#091423] mb-1">
                        品牌：{item.brand || "未知品牌"}
                      </p>
                      <p className="text-[#091423] mb-1">
                        产地：{item.model || "无规格"}
                      </p>
                      <p className="text-[#095CDC] mb-2">
                        {item.gradeName || "等级认证"}
                      </p>
                      <div className="flex space-x-2 mt-3">
                        {allGrades.map((gradeInfo) => (
                          <span
                            key={gradeInfo.grade}
                            className={`px-3 py-1 text-white rounded transform skew-x-22 text-lg font-medium transition-all duration-200 ${
                              currentGrade === gradeInfo.grade
                                ? "h-8 scale-110 shadow-md"
                                : "h-6 opacity-80"
                            }`}
                            style={{
                              backgroundColor: gradeInfo.color,
                              lineHeight:
                                currentGrade === gradeInfo.grade
                                  ? "24px"
                                  : "18px",
                            }}
                          >
                            <span className="transform -skew-x-22 inline-block">
                              {gradeInfo.label}
                            </span>
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* 分页 */}
            {totalItems > pageSize && (
              <div className="flex justify-center">
                <Pagination
                  current={currentPage}
                  total={totalItems}
                  pageSize={pageSize}
                  onChange={handlePageChange}
                  showSizeChanger={false}
                  showQuickJumper
                  showTotal={(total, range) =>
                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                  }
                />
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default FavoritesPage;
